require("dotenv").config();
const mongoose = require('mongoose');

// 导入所有需要更新的模型
const ArticleModel = require('./model/ArticleModel');
const CategoryModel = require('./model/CategoryModel');
const TagModel = require('./model/TagModel');
const JournalModel = require('./model/JournalModel');
const AnimationModel = require('./model/AnimationModel');
const FriendLinkModel = require('./model/FriendLinkModel');
const ProjectModel = require('./model/ProjectModel');
const ResumeModel = require('./model/ResumeModel');
const ArticleCommentModel = require('./model/ArticleComment');
const TrendsModel = require('./model/TrendsModel');
const TrendsCommentModel = require('./model/TrendsComment');
const ImageModel = require('./model/ImageModel');
const ImageCategoryModel = require('./model/ImageCategory');
const GuestbookModel = require('./model/guestbookModel');
const UserModel = require('./model/UserModel');

// 数据库连接
const dbPort = process.env.NODE_ENV === 'prod' ? '40802' : '27017';
const dbUri = `mongodb://localhost:${dbPort}/MyBlog`;
console.log(`📦 连接数据库: ${dbUri}`);

// 连接数据库并等待连接成功
mongoose.connect(dbUri).then(() => {
    console.log('✅ 数据库连接成功\n');
    migrateData();
}).catch((err) => {
    console.error('❌ 数据库连接失败:', err);
    process.exit(1);
});

async function migrateData() {
    try {
        console.log('🚀 开始数据迁移...\n');

        // 1. 查找 admin 用户
        console.log('1️⃣ 查找 admin 用户...');
        const adminUser = await UserModel.findOne({ username: 'admin' });
        
        if (!adminUser) {
            console.error('❌ 未找到 admin 用户，请先创建 admin 用户！');
            process.exit(1);
        }
        
        const adminUserId = adminUser._id;
        console.log(`✅ 找到 admin 用户，ID: ${adminUserId}\n`);

        // 2. 更新各个集合
        const collections = [
            {
                name: 'Articles (文章)',
                model: ArticleModel,
                field: 'authorID'
            },
            {
                name: 'Categories (文章分类)',
                model: CategoryModel,
                field: 'userID'
            },
            {
                name: 'Tags (标签)',
                model: TagModel,
                field: 'userID'
            },
            {
                name: 'Journals (日志)',
                model: JournalModel,
                field: 'userID'
            },
            {
                name: 'Animations (动画)',
                model: AnimationModel,
                field: 'userID'
            },
            {
                name: 'FriendLinks (友情链接)',
                model: FriendLinkModel,
                field: 'userID'
            },
            {
                name: 'Projects (项目)',
                model: ProjectModel,
                field: 'userID'
            },
            {
                name: 'Resumes (简历)',
                model: ResumeModel,
                field: 'userID'
            },
            {
                name: 'ArticleComments (文章评论)',
                model: ArticleCommentModel,
                field: 'userID'
            },
            {
                name: 'Trends (动态)',
                model: TrendsModel,
                field: 'userID'
            },
            {
                name: 'TrendsComments (动态评论)',
                model: TrendsCommentModel,
                field: 'userID'
            },
            {
                name: 'Images (图片)',
                model: ImageModel,
                field: 'userID'
            },
            {
                name: 'ImageCategories (图片分类)',
                model: ImageCategoryModel,
                field: 'userID'
            },
            {
                name: 'Guestbooks (留言板)',
                model: GuestbookModel,
                field: 'userID'
            }
        ];

        console.log('2️⃣ 开始更新数据...\n');

        for (const collection of collections) {
            try {
                // 统计需要更新的文档数量
                const filter = {};
                filter[collection.field] = { $exists: false };
                
                const count = await collection.model.countDocuments(filter);
                
                if (count === 0) {
                    console.log(`⏭️  ${collection.name}: 无需更新 (0条记录)`);
                    continue;
                }

                // 更新数据
                const updateData = {};
                updateData[collection.field] = adminUserId;
                
                const result = await collection.model.updateMany(filter, { $set: updateData });
                
                console.log(`✅ ${collection.name}: 已更新 ${result.modifiedCount} 条记录`);
            } catch (error) {
                console.error(`❌ ${collection.name}: 更新失败 - ${error.message}`);
            }
        }

        console.log('\n3️⃣ 验证数据...\n');

        // 验证更新结果
        for (const collection of collections) {
            try {
                const filter = {};
                filter[collection.field] = { $exists: false };
                const remainingCount = await collection.model.countDocuments(filter);
                
                if (remainingCount > 0) {
                    console.log(`⚠️  ${collection.name}: 仍有 ${remainingCount} 条记录未设置用户ID`);
                } else {
                    const totalCount = await collection.model.countDocuments({});
                    console.log(`✅ ${collection.name}: 所有记录 (${totalCount}条) 已设置用户ID`);
                }
            } catch (error) {
                console.error(`❌ ${collection.name}: 验证失败 - ${error.message}`);
            }
        }

        console.log('\n✨ 数据迁移完成！');
        process.exit(0);
    } catch (error) {
        console.error('❌ 迁移失败:', error);
        process.exit(1);
    }
}

